package com.eric.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eric.domain.dto.*;
import com.eric.domain.po.*;
import com.eric.mapper.MaterialMapper;
import com.eric.mapper.MaterialOutMapper;
import com.eric.service.*;
import com.eric.utils.PublicTools;
import com.eric.utils.ServerBASEURL;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.method.mp.SelectList;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.DeleteJoinWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import static com.eric.utils.Constant.PAGE_CURRENT;
import static com.eric.utils.Constant.PAGE_SIZE;

/**
 * <p>
 * 出库表单 服务实现类
 * </p>
 *
 * @author 新哥
 * @since 2024-03-12
 */
@Service
@RequiredArgsConstructor
public class MaterialOutServiceImpl extends MPJBaseServiceImpl<MaterialOutMapper, MaterialOut> implements IMaterialOutService {
    //    配置encode的前缀
    private final static String ENCODE_PREFIX="MATERIALOUT";
    private final MaterialMapper materialMapper;
    //    用于创建服务器磁盘的文件夹
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
    //    用于做图片文件的文件名
    SimpleDateFormat photoDf = new SimpleDateFormat("yyyyMMdd");

    SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    //   判断当前用户权限的布尔值,用于通过登录用户的权限，选择性地决定是否通过location查询数据
//    private final boolean ROLE_FLAG= PublicTools.checkLoginRole();

    @Value("${file.location}")
    String fileLocation;

    //     创建用于创建服务器磁盘文件夹
    String materialOutPhotoPath="/materialOutPhotos";
    //    调用materialPhotoService，用于存储图片
    private final IMaterialOutPhotoService materialOutPhotoService;

    //    通过userService获取到真是名称用于equipment中的create_by和last_update_by
    private final ISysUserService userService;

    //    最后需要操作material表
    private final IMaterialService materialService;

    private final ILocationService locationService;


    @Override
    @Transactional
    public SaResult saveOneService(MaterialOutDto materialOutDto, MultipartFile[] photoFiles, HttpServletRequest request) {

        //        主要问题是表单出库的数量，不能多余material表中原先数量，所以要先检查原来material中的数量
        MaterialOutDto checkedDto = checkDto(materialOutDto);

        if (BeanUtil.isEmpty(checkedDto)) {
            return SaResult.error("对象不能为空");
        }
        if (StrUtil.isBlank(checkedDto.getMaterialName())){
            return SaResult.error("材料名称不能为空");
        }
        if (StrUtil.isBlank(checkedDto.getBrand())){
            return SaResult.error("品牌名字不能为空");
        }
        if (checkedDto.getNumber()<=0){
            return SaResult.error("数量不能为空或者不能小于等于零");
        }
        if (StrUtil.isBlank(checkedDto.getModel())){
            return SaResult.error("材料型号不能为空");
        }

        String encode_suffix = RandomUtil.randomString(5).toUpperCase();
        String DateFormat = photoDf.format(new Date());
        String materialOut_code=ENCODE_PREFIX+ DateFormat+encode_suffix;
        checkedDto.setEncode(materialOut_code);

//        获取到当前登录用户的userId
        int userId = Integer.parseInt(StpUtil.getLoginId().toString());
        String locationAddress = locationService.getAllByLoginId();

        System.out.println(userId);
        System.out.println(locationAddress);

        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }

//        把前端表单传来的materialOutDto转换为checkedDto对象转换为materialOut对象
        MaterialOut materialOut = BeanUtil.copyProperties(checkedDto, MaterialOut.class);
        materialOut.setCreateBy(userService.getById(userId).getRealName());
        materialOut.setWarehouse(locationAddress);


//        判断checkedDto中number比起material中的number，那个大
        double numberInMaterialOutDto = materialOut.getNumber();
//       通过materialId查询material对象
        SaResult byMaterialNameService = materialService.getOneByIdService(materialOut.getMaterialId());

        Object data = byMaterialNameService.getData();
        if (BeanUtil.isEmpty(data)){
            return SaResult.error("材料库中没有此项材料");
        }
        Material material = BeanUtil.copyProperties(data, Material.class);

        if (material.getNumber()<numberInMaterialOutDto){
            return SaResult.error("表单中出仓数量大于库存数量");
        }

//     todo  这段代码要好好看看，这个photoFiles应该永远不等于null,,,,,photoList!=null&&photoList.length>0
        if (photoFiles!=null){
            fileOperation(materialOut_code,photoFiles,request);
        }
//        把前端表单传来的MaterialInDto对象转换为MaterialIn对象
        MaterialOut materialOutFinal = BeanUtil.copyProperties(checkedDto, MaterialOut.class);
        materialOutFinal.setCreateBy(userService.getById(userId).getRealName());
        materialOutFinal.setWarehouse(locationService.getAllByLoginId());
//        把materialOut对象存进数据库

        save(materialOutFinal);
//       原material的number设置为原表单
        material.setNumber(material.getNumber()-numberInMaterialOutDto);
        materialService.updateById(material);
        return SaResult.ok("succeed!");

    }

    @Override
    @Transactional
    public SaResult modifyOneService(MaterialOutDto materialOutDto, MultipartFile[] photoFiles, HttpServletRequest request, String[] photoList) {

        MaterialOutDto checkedDto = checkDto(materialOutDto);
        if (BeanUtil.isEmpty(checkedDto)) {
            return SaResult.error("对象不能为空");
        }
        if (checkedDto.getId()==null||checkedDto.getId()<=0){
            return SaResult.error("id值不符合要求");
        }
        MaterialOut materialOut = query().eq("id", checkedDto.getId()).one();

        if (BeanUtil.isEmpty(materialOut)) {
            return SaResult.error("没有此表单，请核实");
        }
        if (!checkedDto.getEncode().equals(materialOut.getEncode())){
            return SaResult.error("encode和数据库中的encode不匹配");
        }

//        获取数据库materialOut中number的值
        double numberInMaterialOut = checkedDto.getOriginNumber();

//        获取传进来的表单对象的number值
        double numberInCheckDto = checkedDto.getNumber();


//        通过checkDto中的name查询material表中的number
        MPJLambdaWrapper<Material>wrapper=new MPJLambdaWrapper<Material>()
                .eq(Material::getId,materialOut.getMaterialId());
        Material materialDb = materialMapper.selectOne(wrapper);
//        material表中的number数据
        double numberInMaterial = materialDb.getNumber();

//       前端表单numberInCheckDto和materialOut表中的numberInMaterialOut差值---num1
        double num1=numberInCheckDto-numberInMaterialOut;




//        理清楚这里得逻辑
        /*
         * numberInCheckDto：前端传来的，需要改成得数量
         * numInMaterialOut：数据库中原来materialOut表中number数量
         * numberInMaterial：数据库中material表中的数量
         *num1：前端传来的修改后的number-原始materialOut中的number
         * 如果num1>0,表示出货量增加
         * 如果num1<0，表示出货量减少
         *
         *
         * */
//        1、如果num1>0，表示增大材料出仓量
        if (num1>0){
//         1-1、如果增大的数量Num1比材料表中的Number数值还大，不符合逻辑，返回错误
            if (num1>numberInMaterial){
                return SaResult.error("增加出仓物料的数量比material表中number数据还大，不符合逻辑");
            }

//        1-2、否则，就把材料表中的number-num1,就是材料表中剩下的number
            materialDb.setNumber(numberInMaterial-num1);




//            修改材料表中对应的数据
            materialService.updateById(materialDb);
        }
//        2如果num1<0，表示减少出仓量，原材料表的Number应该加上（-num1）的值才是最后值
        materialDb.setNumber(numberInMaterial-num1);

        materialService.updateById(materialDb);

//        删除前端传进来的文件名的文件
        if (photoList!=null&&photoList.length>0){
            for (String photoUrl : photoList) {
//            1、截取“file/”后面的字符串
                String substring = photoUrl.substring(photoUrl.indexOf("e") + 2);

//            2、删除文件
                FileUtil.del(fileLocation + substring);
            }
            materialOutPhotoService.deleteByPhotoUrlList(Arrays.asList(photoList));
        }
//        把新文件写入数据库
        if (photoFiles!=null){
            fileOperation(checkedDto.getEncode(),photoFiles,request);
        }


//        获取登录用户id
        Object loginId = StpUtil.getLoginId();
        int userId = Integer.parseInt(loginId.toString());
        String realname = userService.getById(userId).getRealName();
//        MaterialOut materialOutNew = BeanUtil.copyProperties(checkedDto, MaterialOut.class);
//        materialOutNew.setLastUpdateBy(realname);

//        这里逻辑，仅仅是更新数量,备注，还有图片，其它的不做修改，前端把其它Input锁死
        MaterialOut materialOutOnlyNum=new MaterialOut();
        materialOutOnlyNum.setId(checkedDto.getId());
        materialOutOnlyNum.setNumber(checkedDto.getNumber());
        materialOutOnlyNum.setDescription(checkedDto.getDescription());
        materialOutOnlyNum.setLastUpdateBy(realname);

        materialOutOnlyNum.setRecipient(materialOutDto.getRecipient());
        materialOutOnlyNum.setReceiveProject(materialOutDto.getReceiveProject());


        boolean updated = updateById(materialOutOnlyNum);

        return updated?SaResult.ok("修改成功"):SaResult.error("修改失败");




    }

    @Override
    @Transactional
    public SaResult deleteOneByIdService(Integer id) {
        if (id==null||id<=0){
            return SaResult.error("id参数错误");
        }
//        这里有逻辑，在删除一条记录时候，material中的Number数据应该也要修改
//        通过id获取materialOut对象
        MaterialOut materialOut = query().eq("id", id).one();

//        获取materialOut表单中的number
        double materialOut_Number = materialOut.getNumber();

//        获取到materialOut的materialName，通过这个name获取到material的name
        String materialOut_Name = materialOut.getMaterialName();
        String materialOut_Model = materialOut.getModel();
        String materialOut_Brand = materialOut.getBrand();
        String materialOut_warehouse = materialOut.getWarehouse();

//        通过materialName获取到查询条件,注意，这个Mater
        MPJLambdaWrapper<Material>wrapper=new MPJLambdaWrapper<Material>()
                .eq(Material::getId,materialOut.getMaterialId());
//        获取到material对象
        Material material = materialService.getOne(wrapper);
        if (!BeanUtil.isEmpty(material)){
            //        获取到material对象中的number
            double material_Number = material.getNumber();

//        逻辑是，由于这是材料入库，删除调一条materialOut表单，意味着material中的number应加上materialOut表单中的materialOutNumber
            material_Number+=materialOut_Number;

            material.setNumber(material_Number);

//        更新material
            materialMapper.updateById(material);
        }

//        material_in_photo同步删除
        DeleteJoinWrapper<MaterialOut>deleteJoinWrapper= JoinWrappers.delete(MaterialOut.class)
                .deleteAll()
                .leftJoin(MaterialOutPhoto.class,MaterialOutPhoto::getMaterialOutEncode,MaterialOut::getEncode)
                .eq(MaterialOut::getId,id);
        deleteJoin(deleteJoinWrapper);
        return SaResult.ok("succeed");
    }

    @Override
    @Transactional
    public SaResult deleteByIdsService(ArrayList<Integer> ids) {

//        todo 逻辑有问题
//        这里有逻辑错误，在删除一条记录时候，material中的Number数据应该也要修改
        if (ids==null||ids.isEmpty()){
            return SaResult.error("id有误");
        }
        for (Integer id : ids) {
//        通过id获取materialIn对象
            MaterialOut materialOut = query().eq("id", id).one();
//        获取materialOut表单中的number
            double materialOutNumber = materialOut.getNumber();
//        通过materialId获取到查询条件
            MPJLambdaWrapper<Material>wrapper=new MPJLambdaWrapper<Material>()
                    .eq(Material::getId, materialOut.getMaterialId());
//        获取到material对象
            Material material = materialService.getOne(wrapper);

//        获取到material对象中的number
            double materialNumber = material.getNumber();

//        逻辑是，由于这是材料出库，删除调一条material出表单，意味着material中的number应加上materialOut表单中的materialOutNumber
            materialNumber+=materialOutNumber;
            material.setNumber(materialNumber);
//        更新material
            materialMapper.updateById(material);

//         material_out_photo被同步删除
            DeleteJoinWrapper<MaterialOut>joinWrapper= JoinWrappers.delete(MaterialOut.class)
                    .deleteAll()
                    .leftJoin(MaterialOutPhoto.class,MaterialOutPhoto::getMaterialOutEncode,MaterialOut::getEncode)
                    .eq(MaterialOut::getId,id);
            deleteJoin(joinWrapper);
        }
        return SaResult.ok("succeed");
    }


    //    todo 这个方法需要修改，应该不用关联photo，排序也有问题
    @Override
    public SaResult getAllByPage(Integer current, Integer pageSize) {
        if (current==null||current<=0){
            current =PAGE_CURRENT ;
        }
        if (pageSize==null||pageSize<=0){
            pageSize = PAGE_SIZE;
        }

        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        Page<MaterialOutDto> page=new Page<>(current,pageSize);
        MPJLambdaWrapper<MaterialOut>wrapper = new MPJLambdaWrapper<MaterialOut>()
                .orderBy(true,false,"id")
                .selectAll(MaterialOut.class)
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
//                .groupBy("create_time")
                .orderByDesc("create_time");

        Page<MaterialOutDto> materialOutDtoPage = selectJoinListPage(page, MaterialOutDto.class, wrapper);
        List<MaterialOutDto> materialOutDtoList =materialOutDtoPage.getRecords();
        return SaResult.data(materialOutDtoList);
    }

    @Override
    public SaResult getOneByIdService(Integer id) {

        if (id==null||id<=0){
            return SaResult.error("id错误");
        }
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        MPJLambdaWrapper<MaterialOut>wrapper=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
                .selectCollection(MaterialOutPhoto.class,MaterialOutDto::getMaterialOutPhotoList)
                .eq(MaterialOut::getId,id)
                .leftJoin(MaterialOutPhoto.class,MaterialOutPhoto::getMaterialOutEncode,MaterialOut::getEncode);
        MaterialOutDto materialOutDto = selectJoinOne(MaterialOutDto.class, wrapper);

        if (BeanUtil.isEmpty(materialOutDto)){
            return SaResult.ok("没有此项记录！");
        }


        List<MaterialOutPhoto> materialOutPhotoList = materialOutDto.getMaterialOutPhotoList();



        if(materialOutPhotoList.size()==1&&materialOutPhotoList.get(0).getMaterialOutEncode()==null){
            materialOutPhotoList.remove(0);
            return SaResult.data(materialOutDto);
        }

        else if(!BeanUtil.isEmpty(materialOutPhotoList)) {
            for (MaterialOutPhoto materialOutPhoto : materialOutPhotoList) {
                String photoUrl = materialOutPhoto.getPhotoUrl();
                materialOutPhoto.setPhotoUrl(ServerBASEURL.BASEURL+photoUrl);
            }
            return SaResult.data(materialOutDto);
        }
        else {
            return SaResult.data(materialOutDto);
        }

    }

    @Override
    public SaResult getByCreateTimeService(Date createTime, Integer current, Integer pageSize) {
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
//        当前端传来的是Date格式日期数据时，由于springMvc正常情况下是无法解析Date数据，需要转换，所以在controller的参数列表中
//       在Date参数前要加注解@DateTimeFormat(iso=DateTimeFormat.ISO.DATE)，看下面：
//        (@DateTimeFormat(iso=DateTimeFormat.ISO.DATE) Date createTime, Integer current, Integer pageSize)
//        把前端传来的时间格式化为指定格式，这里指定格式是timeFormat模式，即在类中公共字段
//        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = timeFormat.format(createTime);
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
//        创建分页对象
        Page<MaterialOutDto>page=new Page<>(current,pageSize);
//        创建查询条件对象
        MPJLambdaWrapper<MaterialOut>wrapper=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
//                记住，create_time前要加一个t.否则后面连接查询时，equip_transfer表和equip_transfer_photo表中都有create_time，会致使字段模糊，搞不清楚是那个表的create_tiem
//                这个是查指定日期的中的数据
                .apply("date_format(t.create_time,'%y%m%dd')=" + "date_format('" + format + "','%y%m%dd')")
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
                .selectCollection(MaterialOutPhoto.class,MaterialOutDto::getMaterialOutPhotoList)
                .leftJoin(MaterialOutPhoto.class,MaterialOutPhoto::getMaterialOutEncode,MaterialOut::getEncode);
        Page<MaterialOutDto> materialOutDtoPage = selectJoinListPage(page, MaterialOutDto.class, wrapper);
        List<MaterialOutDto> records = materialOutDtoPage.getRecords();
        List<MaterialOutDto> materialOutDtoList = BeanUtil.copyToList(records, MaterialOutDto.class);
        return SaResult.data(materialOutDtoList);
    }

    @Override
    public SaResult getByUpdateTimeService(Date updateTime, Integer current, Integer pageSize) {
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }

//        当前端传来的是Date格式日期数据时，由于springMvc正常情况下是无法解析Date数据，需要转换，所以在controller的参数列表中
//       在Date参数前要加注解@DateTimeFormat(iso=DateTimeFormat.ISO.DATE)，看下面：
//        (@DateTimeFormat(iso=DateTimeFormat.ISO.DATE) Date createTime, Integer current, Integer pageSize)
//        把前端传来的时间格式化为指定格式，这里指定格式是timeFormat模式，即在类中公共字段
//        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = timeFormat.format(updateTime);
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
//        创建分页对象
        Page<MaterialOutDto>page=new Page<>(current,pageSize);
//        创建查询条件对象
        MPJLambdaWrapper<MaterialOut>wrapper=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
//                记住，create_time前要加一个t.否则后面连接查询时，equip_transfer表和equip_transfer_photo表中都有create_time，会致使字段模糊，搞不清楚是那个表的create_tiem
//                这个是查指定日期的中的数据
                .apply("date_format(t.update_time,'%y%m%dd')=" + "date_format('" + format + "','%y%m%dd')")
//                下面的都是分页连接查询的普通步骤了
                .selectCollection(MaterialOutPhoto.class,MaterialOutDto::getMaterialOutPhotoList)
                .leftJoin(MaterialOutPhoto.class,MaterialOutPhoto::getMaterialOutEncode,MaterialOut::getEncode);
        Page<MaterialOutDto> materialOutDtoPage = selectJoinListPage(page, MaterialOutDto.class, wrapper);
        List<MaterialOutDto> records = materialOutDtoPage.getRecords();
        List<MaterialOutDto> materialOutDtoList = BeanUtil.copyToList(records, MaterialOutDto.class);
        return SaResult.data(materialOutDtoList);

    }

    @Override
    public SaResult getByMaterialNameService(String materialName, Integer current, Integer pageSize) {
        String materialNameTrim = StrUtil.trim(materialName);
        if (StrUtil.isBlank(materialNameTrim)) {
            return SaResult.error("材料名不能为空");
        }
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        Page<MaterialOutDto>page=new Page<>(current,pageSize);
//        创建查询条件对象
        MPJLambdaWrapper<MaterialOut>wrapper=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
                .like("material_name",materialNameTrim)
//                下面的都是分页连接查询的普通步骤了
                .selectCollection(MaterialOutPhoto.class,MaterialOutDto::getMaterialOutPhotoList)
                .leftJoin(MaterialOutPhoto.class,MaterialOutPhoto::getMaterialOutEncode,MaterialOut::getEncode);
        Page<MaterialOutDto> materialOutDtoPage = selectJoinListPage(page, MaterialOutDto.class, wrapper);
        List<MaterialOutDto> records = materialOutDtoPage.getRecords();
        List<MaterialOutDto> materialOUtDtoList = BeanUtil.copyToList(records, MaterialOutDto.class);
        return SaResult.data(materialOUtDtoList);
    }

    @Override
    public SaResult getByLastUpdateByService(String lastByName, Integer current, Integer pageSize) {
        if ( StrUtil.isBlank(StrUtil.trim(lastByName))){
            return SaResult.error("人名不能为空");
        }
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
//        创建分页对象
        Page<MaterialOutDto>page=new Page<>(current,pageSize);

        //        创建查询条件对象
        MPJLambdaWrapper<MaterialOut>wrapper=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
                .like("last_update_by",lastByName)
//                下面的都是分页连接查询的普通步骤了
                .selectCollection(MaterialOutPhoto.class,MaterialOutDto::getMaterialOutPhotoList)
                .leftJoin(MaterialOutPhoto.class,MaterialOutPhoto::getMaterialOutEncode,MaterialOut::getEncode);
        Page<MaterialOutDto> materialOutDtoPage = selectJoinListPage(page, MaterialOutDto.class, wrapper);
        List<MaterialOutDto> records = materialOutDtoPage.getRecords();
        List<MaterialOutDto> materialOUtDtoList = BeanUtil.copyToList(records, MaterialOutDto.class);
        return SaResult.data(materialOUtDtoList);
    }

    @Override
    public SaResult getByCreateByService(String createByName, Integer current, Integer pageSize) {
        if ( StrUtil.isBlank(StrUtil.trim(createByName))){
            return SaResult.error("人名不能为空");
        }
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
//        创建分页对象
        Page<MaterialOutDto>page=new Page<>(current,pageSize);

        //        创建查询条件对象
        MPJLambdaWrapper<MaterialOut>wrapper=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
                .like("create_by",createByName)
//                下面的都是分页连接查询的普通步骤了
                .selectCollection(MaterialOutPhoto.class,MaterialOutDto::getMaterialOutPhotoList)
                .leftJoin(MaterialOutPhoto.class,MaterialOutPhoto::getMaterialOutEncode,MaterialOut::getEncode);
        Page<MaterialOutDto> materialOutDtoPage = selectJoinListPage(page, MaterialOutDto.class, wrapper);
        List<MaterialOutDto> records = materialOutDtoPage.getRecords();
        List<MaterialOutDto> materialOUtDtoList = BeanUtil.copyToList(records, MaterialOutDto.class);
        return SaResult.data(materialOUtDtoList);
    }

    @Override
    public SaResult getAllByMoon(Date moonDate, Integer current, Integer pageSize) {
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
        String format = timeFormat.format(moonDate);
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }

        //        创建分页对象
        Page<MaterialOutDto>page=new Page<>(current,pageSize);

        MPJLambdaWrapper<MaterialOut>wrapper=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
//                记住，create_time前要加一个t.否则后面连接查询时，equip_transfer表和equip_transfer_photo表中都有create_time，会致使字段模糊，搞不清楚是那个表的create_tiem
//                这个是查指定日期的中的数据
//                queryWrapper.apply(" date_format(create_at,'%y%mm%') = date_format('" + withdrawRecord.getCreateAt() + "-01','%y%mm%')");

                .apply("date_format(t.create_time,'%y%m%')=" + "date_format('" + format + "','%y%m%')")
//                下面的都是分页连接查询的普通步骤了
                .selectCollection(MaterialOutPhoto.class,MaterialOutDto::getMaterialOutPhotoList)
                .leftJoin(MaterialOutPhoto.class,MaterialOutPhoto::getMaterialOutEncode,MaterialOut::getEncode);
        Page<MaterialOutDto> materialOutDtoPage = selectJoinListPage(page, MaterialOutDto.class, wrapper);
        List<MaterialOutDto> records = materialOutDtoPage.getRecords();
        List<MaterialOutDto> materialOUtDtoList = BeanUtil.copyToList(records, MaterialOutDto.class);
        return SaResult.data(materialOUtDtoList);
    }

    @Override
    public SaResult getByTypeName(String parentType, String childTypeName, Integer orderBy, Integer current, Integer pageSize) {
        if (StrUtil.isEmpty(parentType) && StrUtil.isEmpty(childTypeName)) {
            return SaResult.error("类型名称不能为空");
        }
        if (current==null||current<=0){
            current = PAGE_CURRENT;
        }
        if (pageSize==null||pageSize<=0){
            pageSize = PAGE_SIZE;
        }
        if (orderBy==null||orderBy<=0){
            return SaResult.error("orderBy值不能为空或者小于等于零！");
        }
        boolean desc=true;
        boolean asc=false;
        if (orderBy!=1){
            desc=false;
            asc=true;
        }
        String fullTypeName = parentType+":"+childTypeName;

        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }

        Page<MaterialOut>page=new Page<>(current,pageSize);
        QueryWrapper<MaterialOut> wrapper=new QueryWrapper<>();
        wrapper.eq("type_name",fullTypeName)
                .eq(!PublicTools.checkLoginRole(),"warehouse",locationAddress)
                .orderByDesc(desc,"number")
                .orderByAsc(asc,"number");
        List<MaterialOut> materialOutList = page(page, wrapper).getRecords();
        List<MaterialOutDto> materialOutDtoList = BeanUtil.copyToList(materialOutList, MaterialOutDto.class);
        return SaResult.data(materialOutDtoList);
    }

    @Override
    public SaResult getAllCountsService() {
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        MPJLambdaWrapper<MaterialOut>wrapper=new MPJLambdaWrapper<MaterialOut>()
                .select( "count(id)")
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse, locationAddress);
        Long l = selectJoinOne(Long.class, wrapper);
        return SaResult.data(l);
    }

    @Override
    public SaResult getAllByMultifunctionNameService(String name, Integer current, Integer pageSize) {
        if ( StrUtil.isBlank(StrUtil.trim(name))){
            return SaResult.error("查询名不能为空");
        }
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }

        Page<MaterialOutDto>page=new Page<>(current,pageSize);
        Set<MaterialOutDto>finalResultList=new HashSet<>();
//        这个是判断当前用户是否已经分配了项目或者仓库，如果没有，返回一个错误
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址，不能查询！");
        }

        //        根据材料名查询
        MPJLambdaWrapper<MaterialOut>wrapperByMaterialName=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .like("material_name",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
//                .groupBy("create_time")
                .orderByDesc("create_time");
        Page<MaterialOutDto> materialDtoPageByMaterialName = selectJoinListPage(page, MaterialOutDto.class, wrapperByMaterialName);
        List<MaterialOutDto> materialDtoListByMaterialName =materialDtoPageByMaterialName.getRecords();
        if (!materialDtoListByMaterialName.isEmpty()){
            finalResultList.addAll(materialDtoListByMaterialName);
        }

        //        根据创建人名查询
        MPJLambdaWrapper<MaterialOut>wrapperByCreateBy=new MPJLambdaWrapper<MaterialOut>( )
                .selectAll(MaterialOut.class)
                .like("create_by",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
//                .groupBy("create_time")
                .orderByDesc("create_time");
        Page<MaterialOutDto> materialDtoPageByCreateBy = selectJoinListPage(page, MaterialOutDto.class, wrapperByCreateBy);
        List<MaterialOutDto> materialDtoListByCreateBy =materialDtoPageByCreateBy.getRecords();
        if (!materialDtoListByCreateBy.isEmpty()){
            finalResultList.addAll(materialDtoListByCreateBy);
        }


//    根据最后修改人查询

        MPJLambdaWrapper<MaterialOut>wrapperByLastUpdateBy=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .like("last_update_by",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
//                .groupBy("create_time")
                .orderByDesc("create_time");
        Page<MaterialOutDto> materialDtoPageByLastUpdateBy = selectJoinListPage(page, MaterialOutDto.class, wrapperByLastUpdateBy);
        List<MaterialOutDto> materialDtoListByLastUpdateBy =materialDtoPageByLastUpdateBy.getRecords();
        if (!materialDtoListByLastUpdateBy.isEmpty()){
            finalResultList.addAll(materialDtoListByLastUpdateBy);
        }
        //    根据品牌查询

        MPJLambdaWrapper<MaterialOut>wrapperByBrand=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .like("brand",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
//                .groupBy("create_time")
                .orderByDesc("create_time");
        Page<MaterialOutDto> materialDtoPageByBrand = selectJoinListPage(page, MaterialOutDto.class, wrapperByBrand);
        List<MaterialOutDto> materialDtoListByBrand =materialDtoPageByBrand.getRecords();
        if (!materialDtoListByBrand.isEmpty()){
            finalResultList.addAll(materialDtoListByBrand);
        }


        //    根据接收项目查询

        MPJLambdaWrapper<MaterialOut>wrapperByReceiveProject=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .like("receive_project",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
//                .groupBy("create_time")
                .orderByDesc("create_time");
        Page<MaterialOutDto> materialDtoPageByReceiveProject = selectJoinListPage(page, MaterialOutDto.class, wrapperByReceiveProject);
        List<MaterialOutDto> materialDtoListByReceiveProject =materialDtoPageByReceiveProject.getRecords();
        if (!materialDtoListByReceiveProject.isEmpty()){
            finalResultList.addAll(materialDtoListByReceiveProject);
        }

        //    根据typeName查询

        MPJLambdaWrapper<MaterialOut>wrapperByTypeName=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .like("type_name",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
//                .groupBy("create_time")
                .orderByDesc("create_time");
        Page<MaterialOutDto> materialDtoPageByTypeName = selectJoinListPage(page, MaterialOutDto.class, wrapperByTypeName);
        List<MaterialOutDto> materialDtoListByTypeName =materialDtoPageByTypeName.getRecords();
        if (!materialDtoListByTypeName.isEmpty()){
            finalResultList.addAll(materialDtoListByTypeName);
        }

        //        根据领取人查询
        MPJLambdaWrapper<MaterialOut>wrapperByRecipient=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .like("recipient",name)
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
                .orderByDesc("create_time");

        Page<MaterialOutDto> materialDtoPageByRecipient = selectJoinListPage(page, MaterialOutDto.class, wrapperByRecipient);
        List<MaterialOutDto> materialDtoListByRecipient =materialDtoPageByRecipient.getRecords();
        if (!materialDtoListByRecipient.isEmpty()){
            finalResultList.addAll(materialDtoListByRecipient);
        }
        List<MaterialOutDto>materialOutDTOs=new ArrayList<>(finalResultList);


        //        对List内部元素重新按照创建时间从晚到早重新排序
        materialOutDTOs.sort(new Comparator<MaterialOutDto>() {
            @Override
            public int compare(MaterialOutDto o1, MaterialOutDto o2) {
                Date createTime1 = o1.getUpdateTime();
                Date createTime2 = o2.getUpdateTime();
                return createTime2.compareTo(createTime1);
            }
        });

        return SaResult.data(materialOutDTOs);
    }

    @Override
    public  SaResult getAllCountsByMultifunctionNameService(String name,Integer current,Integer pageSize){
        if ( StrUtil.isBlank(StrUtil.trim(name))){
            return SaResult.error("查询名不能为空");
        }
        Set<MaterialOut>finalResultList=new HashSet<>();
        //        这个是判断当前用户是否已经分配了项目或者仓库，如果没有，返回一个错误
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址，不能查询！");
        }
        //        根据材料名查询
        MPJLambdaWrapper<MaterialOut>wrapperByMaterialName=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .like("material_name",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress);
        List<MaterialOut> materialOutListByMaterialName =list(wrapperByMaterialName);
        if (!materialOutListByMaterialName.isEmpty()){
            finalResultList.addAll(materialOutListByMaterialName);
        }

        //        根据材料名查询
        MPJLambdaWrapper<MaterialOut>wrapperByCreateBy=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .like("create_by",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress);
        List<MaterialOut> materialOutListByCreateBy =list(wrapperByCreateBy);
        if (!materialOutListByCreateBy.isEmpty()){
            finalResultList.addAll(materialOutListByCreateBy);
        }

        //        根据最后修改人
        MPJLambdaWrapper<MaterialOut>wrapperByLastUpdateBy=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .like("last_update_by",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress);
        List<MaterialOut> materialOutListByLastUpdateBy =list(wrapperByLastUpdateBy);
        if (!materialOutListByLastUpdateBy.isEmpty()){
            finalResultList.addAll(materialOutListByLastUpdateBy);
        }


        //        根据最后修改人
        MPJLambdaWrapper<MaterialOut>wrapperByBrand=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .like("brand",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress);
        List<MaterialOut> materialOutListByBrand =list(wrapperByBrand);
        if (!materialOutListByBrand.isEmpty()){
            finalResultList.addAll(materialOutListByBrand);
        }

        //        根据encode
        MPJLambdaWrapper<MaterialOut>wrapperByEncode=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .like("encode",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress);
        List<MaterialOut> materialOutListByEncode =list(wrapperByEncode);
        if (!materialOutListByEncode.isEmpty()){
            finalResultList.addAll(materialOutListByEncode);
        }

        //        根据typeName
        MPJLambdaWrapper<MaterialOut>wrapperByTypeName=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .like("type_name",name)
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress);
        List<MaterialOut> materialOutListByTypeName =list(wrapperByTypeName);
        if (!materialOutListByTypeName.isEmpty()){
            finalResultList.addAll(materialOutListByTypeName);
        }

//        根据领取人
        MPJLambdaWrapper<MaterialOut>wrapperByRecipient=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .like("recipient",name)
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress);
        List<MaterialOut> materialOutListByRecipient =list(wrapperByRecipient);
        if (!materialOutListByRecipient.isEmpty()){
            finalResultList.addAll(materialOutListByRecipient);
        }

        List<MaterialOut>materialOutList=new ArrayList<>(finalResultList);
        return SaResult.data((long)materialOutList.size());
    }

    @Override
    public SaResult getByBetweenTimesService(Date start, Date end, Integer current, Integer pageSize) {
        if (current == null) {
            current = PAGE_CURRENT;
        }
        if (pageSize == null) {
            pageSize = PAGE_SIZE;
        }
        if (BeanUtil.isEmpty(start) || BeanUtil.isEmpty(end)) {
            return SaResult.error("日期为空，请核实！");
        }
        if (end.before(start)) {
            Date temp;
            temp=start;
            start=end;
            end=temp;
        }
        String startFormat = timeFormat.format(start);
        String endFormat = timeFormat.format(end);

        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }

        Page<MaterialOutDto>page=new Page<>(current,pageSize);
//       创建查询对象
        MPJLambdaWrapper<MaterialOut>wrapper=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .apply("date_format(t.create_time,'%y%m%d') >= date_format('" +startFormat + "','%y%m%d')")
                .apply("date_format(t.create_time,'%y%m%d') <= date_format('" + endFormat + "','%y%m%d')")
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress)
//                .groupBy("create_time")
                .orderByDesc("create_time")
//                .selectCollection(MaterialInPhoto.class,MaterialInDto::getMaterialInPhotoList)
//                .leftJoin(MaterialInPhoto.class,MaterialInPhoto::getMaterialInEncode,MaterialIn::getEncode)
                ;
        Page<MaterialOutDto> materialOutDtoPage = selectJoinListPage(page, MaterialOutDto.class, wrapper);
        List<MaterialOutDto> records = materialOutDtoPage.getRecords();
        List<MaterialOutDto> materialOutDtoList = BeanUtil.copyToList(records, MaterialOutDto.class);
        return SaResult.data(materialOutDtoList);




    }


    @Override
    public SaResult getAllCountsByBetweenTimes(Date start, Date end) {
        if (BeanUtil.isEmpty(start) || BeanUtil.isEmpty(end)) {
            return SaResult.error("日期为空，请核实！");
        }
        if (end.before(start)) {
            Date temp;
            temp=start;
            start=end;
            end=temp;
        }
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        String startFormat = timeFormat.format(start);
        String endFormat = timeFormat.format(end);
        MPJLambdaWrapper<MaterialOut>wrapper=new MPJLambdaWrapper<MaterialOut>()
                .select("count(id)")
                .apply("date_format(t.create_time,'%y%m%d') >= date_format('" +startFormat + "','%y%m%d')")
                .apply("date_format(t.create_time,'%y%m%d') <= date_format('" + endFormat + "','%y%m%d')")
//                下面的都是分页连接查询的普通步骤了
                .eq(!PublicTools.checkLoginRole(),MaterialOut::getWarehouse,locationAddress);
//        Long l = selectJoinCount(wrapper);
        Long l = selectJoinOne(Long.class, wrapper);
        return SaResult.data(l);
    }

    @Override
    public SaResult getMaterialOutListByMaterialId(boolean timeStatus,Integer materialId, Integer current, Integer pageSize, String projectName, String recipient,Date start, Date end) {

        System.out.println(start);
        System.out.println(end);


        if (current==null||current<=0){
            current = PAGE_CURRENT;
        }
        if (pageSize==null||pageSize<=0){
            pageSize = PAGE_SIZE;
        }

        String startFormat =null;
        String endFormat=null;
        if (StrUtil.isBlank(projectName)){
            projectName=null;
        }

        if (StrUtil.isBlank(projectName)){
            projectName=null;
        }

        if (timeStatus){
            if (end.before(start)) {
                Date temp;
                temp=start;
                start=end;
                end=temp;
            }
            startFormat=timeFormat.format(start);
            endFormat=timeFormat.format(end);
        }


        Page<MaterialOut>page=new Page<>(current,pageSize);

        MPJLambdaWrapper<MaterialOut>wrapper=new MPJLambdaWrapper<MaterialOut>()
                .selectAll(MaterialOut.class)
                .apply(timeStatus,"date_format(t.create_time,'%y%m%d') >= date_format('" +startFormat + "','%y%m%d')")
                .apply(timeStatus,"date_format(t.create_time,'%y%m%d') <= date_format('" + endFormat + "','%y%m%d')")
                .eq(!StrUtil.isBlank(recipient),MaterialOut::getRecipient,recipient)
                .eq(!StrUtil.isBlank(projectName),MaterialOut::getReceiveProject,projectName)
                .eq(MaterialOut::getMaterialId, materialId);
        Page<MaterialOut> materialOutPage = selectJoinListPage(page, MaterialOut.class, wrapper);
        List<MaterialOut> materialOutList = materialOutPage.getRecords();
        List<MaterialOutDto> materialOutDtoList = BeanUtil.copyToList(materialOutList, MaterialOutDto.class);
        return SaResult.data(materialOutDtoList);

    }



//    todo 这个方法有问题，同时要改进MaterialIn那个方法，等这个完善后在处理
    @Override
    public SaResult getMaterialOutListCountByMaterialId(boolean timeStatus,Integer materialId, String projectName,String recipient, Date start, Date end) {

        String startFormat =null;
        String endFormat=null;
        if (StrUtil.isBlank(projectName)){
            projectName=null;
        }


        if (timeStatus){
            if (end.before(start)) {
                Date temp;
                temp=start;
                start=end;
                end=temp;
            }
            startFormat = timeFormat.format(start);
            endFormat = timeFormat.format(end);
        }
        MPJLambdaWrapper<MaterialOut>wrapper=new MPJLambdaWrapper<MaterialOut>()
                .select("count(id)")
                .apply(timeStatus ,"date_format(t.create_time,'%y%m%d') >= date_format('" +startFormat + "','%y%m%d')")
                .apply(timeStatus,"date_format(t.create_time,'%y%m%d') <= date_format('" + endFormat + "','%y%m%d')")
                .eq(!StrUtil.isBlank(projectName),MaterialOut::getReceiveProject,projectName)
                .eq(!StrUtil.isBlank(recipient),MaterialOut::getRecipient,recipient)
                .eq(MaterialOut::getMaterialId, materialId);
        Long count = selectJoinOne(Long.class, wrapper);

        return SaResult.data(count);
    }

    private MaterialOutDto checkDto(MaterialOutDto materialOutDto){
//        encode
        String materialOutEncodeTrim = StrUtil.trim(materialOutDto.getEncode());
        if (StrUtil.isBlank(materialOutEncodeTrim)) {
            materialOutDto.setEncode(null);
        }else {
            materialOutDto.setEncode(materialOutEncodeTrim);
        }


        String materialNameTrim = StrUtil.trim(materialOutDto.getMaterialName());
        if (StrUtil.isBlank(materialNameTrim)) {
            materialOutDto.setMaterialName(null);
        }
        else {
            materialOutDto.setMaterialName(materialNameTrim);
        }


        String materialBrandTrim = StrUtil.trim(materialOutDto.getBrand());
        if (StrUtil.isBlank(materialBrandTrim)) {materialOutDto.setBrand(null);}
        else {
            materialOutDto.setBrand(materialBrandTrim);
        }


        String materialModelTrim = StrUtil.trim(materialOutDto.getModel());
        if (StrUtil.isBlank(materialModelTrim)) {
            materialOutDto.setModel(null);
        }
        else {
            materialOutDto.setModel(materialModelTrim);
        }

        String materialWarehouseTrim = StrUtil.trim(materialOutDto.getWarehouse());
        if (StrUtil.isBlank(materialWarehouseTrim)) {materialOutDto.setWarehouse(null);}
        else {
            materialOutDto.setWarehouse(materialWarehouseTrim);
        }

        String materialPiecesTrim = StrUtil.trim(materialOutDto.getPieces());
        if (StrUtil.isBlank(materialPiecesTrim)) {materialOutDto.setPieces(null);}
        else {
            materialOutDto.setPieces(materialPiecesTrim);
        }


        String materialReceiveProjectTrim = StrUtil.trim(materialOutDto.getReceiveProject());
        if (StrUtil.isBlank(materialReceiveProjectTrim)) {materialOutDto.setReceiveProject(null);}
        else {
            materialOutDto.setReceiveProject(materialReceiveProjectTrim);
        }

//     todo  描述，如果是""，还是需要设置为null，其它的serviceImpl也应该要这样子改一下
        String materialDescriptionTrim = StrUtil.trim(materialOutDto.getDescription());
        if (StrUtil.isBlank(materialDescriptionTrim)) {materialOutDto.setDescription(null);}


        return materialOutDto;

    }

    private boolean fileOperation(String encode, MultipartFile[] photoFiles, HttpServletRequest request) {
        List<MaterialOutPhotoDto>materialOutPhotoDtoList=new ArrayList<>();
//        创建日期目录
        String format = sdf.format(new Date());
//        详细目录名是date,存储materialPhoto的目录，日期目录，encode目录
        String realPath = fileLocation + materialOutPhotoPath + format + encode;
//        创建文件对象
        File folder = new File(realPath);
//        定义全网络路径
        String url;
//        创建目录
        if (!folder.exists()) {
            folder.mkdirs();
        }
//        把前端传进来的文件列表遍历，并写进硬盘中，同时写入数据库中
        for (MultipartFile multipartFile : photoFiles) {
            MaterialOutPhotoDto materialOutPhotoDto=new MaterialOutPhotoDto();
//            获取文件的原始文件名，并取得文件后缀名，如.jpg
            String originalFilename = multipartFile.getOriginalFilename();
            int i = 0;
            if (originalFilename != null) {
                i = originalFilename.lastIndexOf(".");
            }
            String substring;
            String newFileName = null;
            if (originalFilename != null) {
//             把截取文件名的后缀  “.jpg”
                substring = originalFilename.substring(i).toLowerCase();
//            重新拼接文件名加.jpg，前缀是登录名，如登录名为eric，整照片的全名就是eric.jpg
//            为避免文件名出行由于菜单名称相同，而相同造成覆盖，采用了一个7位的随机字符串拼接
                newFileName = RandomUtil.randomString(4).toUpperCase() +substring;
//            }
                try {
//                    通过transferTo方法，把文件写入磁盘
                    multipartFile.transferTo(new File(folder, newFileName));



//                    图片文件相对路径
                    url = materialOutPhotoPath+ format +encode+"/"+ newFileName;






//                    把url,encode,equipmentPhotoDto写入equipmentPhotoDto对象相应字段中
                    materialOutPhotoDto.setPhotoUrl(url);
                    materialOutPhotoDto.setMaterialOutEncode(encode);
                    materialOutPhotoDtoList.add(materialOutPhotoDto);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
//        把materialPhotoDto列表转换为materialPhoto列表
        List<MaterialOutPhoto> materialOutPhotoList = BeanUtil.copyToList(materialOutPhotoDtoList, MaterialOutPhoto.class);
//        写入数据库
        return materialOutPhotoService.saveBatch(materialOutPhotoList);


    }



}
